import gwc.domain.User



def connectedUsersList = {
	def connectedUsers = context.connectedUsers
	if (connectedUsers == null) {
		connectedUsers = [] as Set
		context.connectedUsers = connectedUsers
	}

	connectedUsers
}

def userAlreadyConnected = {user ->
connectedUsersList().contains(user)
}

def addUser = {user ->
	connectedUsersList() << user
	request.session.user = user
}

if (params.user) {
	def user = User.get(params.user)

	if (user && (user.password == params.password)) {
		if (userAlreadyConnected(user)) {
			request.error = 'user already connected'
		} else {
			addUser(user)

			response.sendRedirect('index.groovy')
		}
	} else {
		request.error = 'user not found'
	}
}

html.html {
	head {}

	body {
		form (action : 'connect.groovy', method : 'post') {
			if (request.error) {
				div (style : 'color : red', request.error)
			}
			div {
				label ('User : ')
				input (type : 'text', name : 'user', value : (params.user ?: ""))
			}
			div {
				label ('Password : ')
				input (type : 'password', name : 'password', value : (params.password ?: ""))
			}
			div {
				input (type : 'submit', value : 'Connect')
				a (href : 'register.groovy', 'Register')
			}
		}
	}
}
